<?php 
namespace plugins\finance\model;

use think\Model;
use think\Db;
use plugins\pay\lib\Pay;
use plugins\finance\model\FinanceAccountsModel;

class FinanceRechargeModel extends Model
{	
	//生成支付记录
	public function recharge($finance_id,$pay_type,$money){
		$this->recharge_num = uniqid('finance_recharge_');
		$this->finance_id = $finance_id;
		$this->recharge_aim = $pay_type;
		//支付账户
		$this->recharge_aim_account = '';
		$this->time = time();
		$this->money = $money;
		$this->status = 1;

		$result = $this->save();

		if($result){
			return ['status'=>true,'message'=>$this->recharge_num];
		}else{
			return ['status'=>false];
		}
	}

	//充值支付退款
	public function rechagreReturn()
	{

        $type = $this->recharge_aim ; 
        $wechatpay= Pay::createInstance(  $type  );	//创建pay的class

        $bizcontent = [];

        //微信
        if($type == 'wechatpay'){
	        $bizcontent['out_trade_no'] = $this->recharge_num;
	        //退款单号
	        $bizcontent['out_refund_no'] = uniqid();

	        //退款金额 分
	        $bizcontent['refund_fee'] = $this->money * 100;

	        //订单总金额
	        $bizcontent['total_fee'] = $this->money * 100;        	
        }

        //支付宝
        if($type == 'alipay'){
			$bizcontent['out_trade_no'] = $this->recharge_num;
			//退款单号
			$bizcontent['out_request_no'] = uniqid();

			$bizcontent['refund_amount'] = $this->money;        	
        }

  		$bizcontent = json_encode($bizcontent);	

  		$res = $wechatpay->refund( $bizcontent );		

  		if($res['return_code'] == 'SUCCESS'){

  			//生成流水
  			//用户财务账户
  			$member_finance = ( new FinanceModel )->get(['finance_id'=>$this->finance_id]);

			$data['remark'] = '充值退款';
			$data['money'] = $this->money;
			$data['member'] = $member_finance->finance_id;
			( new FinanceAccountsModel )->behavior(105,$data);

  			$this->status = 5;
  			$this->save();
  			return ['status'=>true,'message'=>'退款完成'];
  		}

  		if($res['return_code'] == 'FAIL'){
  			return ['status'=>false,'message'=>$res['return_msg']];
  		}

	}
}